package com.cloud.wms.ui.inside.presenter;

import android.text.TextUtils;

import com.cloud.core.base.BaseRxPresenter;
import com.cloud.core.http.error.ApiException;
import com.cloud.core.utils.MessageCreator;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.http.Params;
import com.cloud.wms.http.observer.LoadingObserver;
import com.cloud.wms.http.observer.ResponseWrapper;
import com.cloud.wms.http.observer.RetryWithDelay;
import com.cloud.wms.tools.PageHelper;
import com.cloud.wms.tools.RxUtils;
import com.cloud.wms.tools.TaskHelper;
import com.cloud.wms.ui.inside.contract.LackQueryContract;
import com.cloud.wms.ui.inside.entity.LackCommodityEntity;
import com.cloud.wms.ui.main.entity.RemoteEntity;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.ui.main.entity.UserEntity;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * Created by FC on 2021/3/12.
 * Desc：补货下架
 */
public class LackQueryPresenter extends BaseRxPresenter<LackQueryContract.View> implements LackQueryContract.Presenter {

    public static final int CREATE_REPLENISH_ORDER = 0x107;

    public static final int TASK = 0x108;

    @Inject
    public LackQueryPresenter() {

    }

    @Override
    public void loadLackCommodity(String barCode, int page) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        if (!TextUtils.isEmpty(barCode)) {
            params.put("BarCode", barCode);
        }
        params.put("SkipCount", PageHelper.skipCount(page));
        params.put("MaxResultCount", PageHelper.PAGE_SIZE);
        FineExApplication.component().http()
                .queryLackCommodity(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ArrayList<LackCommodityEntity>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ArrayList<LackCommodityEntity> info) {
                        if (page == 0) {
                            mView.onSuccess(MessageCreator.createMessage(info, PageHelper.LIST_NEW_DATA));
                        } else {
                            mView.onSuccess(MessageCreator.createMessage(info, PageHelper.LIST_NEXT_DATA));
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    @Override
    public void createReplenishOrder(ArrayList<LackCommodityEntity> commodityEntities) {
        ArrayList<Params> list = new ArrayList<>();
        for (int i = 0; i < commodityEntities.size(); i++) {
            Params params = Params.newInstance(Params.Type.MEMBER);
            params.put("replenishPlanIDs", commodityEntities.get(i).getReplenishPlanIDs());
            params.put("commodityID", commodityEntities.get(i).getCommodityId());
            params.put("stockType", commodityEntities.get(i).getStockType());
            params.put("barCode", commodityEntities.get(i).getBarCode());
            params.put("commodityName", commodityEntities.get(i).getCommodityName());
            params.put("productBatchID", commodityEntities.get(i).getProductBatchID());
            params.put("destPosID", commodityEntities.get(i).getDestPosID());
            params.put("destAreaID", commodityEntities.get(i).getDestAreaID());
            params.put("factAmount", commodityEntities.get(i).getPlanAmount() + commodityEntities.get(i).getLackAmount());
            list.add(params);
        }

        FineExApplication.component().http()
                .createReplenishOrder(list)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<Long>(mView.provideContext()) {
                    @Override
                    public void onSuccess(Long info) {
                        loadLackCommodity("", 0);
                        mView.onSuccess(MessageCreator.createMessage(info, CREATE_REPLENISH_ORDER));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    @Override
    public void receiveTask(long billId, String taskCode) {
        FineExApplication
                .component()
                .http()
                .orderTaskList(billId + "")
                .map(new ResponseWrapper<>())
                .map(RemoteEntity::getItems)
                .flatMap((Function<ArrayList<TaskEntity>, ObservableSource<TaskEntity>>) Observable::fromIterable)
                .filter(taskEntity -> taskEntity.getTaskCode().equalsIgnoreCase(taskCode))
                .toList()
                .toObservable()
                .flatMap((Function<List<TaskEntity>, ObservableSource<TaskEntity>>) taskEntities -> {
                    if (taskEntities == null || taskEntities.isEmpty()) {
                        return Observable.error(new ApiException("任务可能暂未生成，请稍后到待办任务中领取"));
                    }
                    TaskEntity taskEntity = taskEntities.get(0);
                    return Observable.just(taskEntity);
                })
                .retryWhen(new RetryWithDelay(5, 1200))
                .flatMap((Function<TaskEntity, ObservableSource<TaskEntity>>) taskEntity -> {
                    Params paramsTask = new Params();
                    paramsTask.put("TaskID", taskEntity.getTaskID());
                    UserEntity userInfo = FineExApplication.component().loginCache().getUserInfo();
                    paramsTask.put("JobStationID", userInfo.getJobStationID());
                    paramsTask.put("ProductCategory", userInfo.getProductCategory());
                    paramsTask.put("ExecutorID", userInfo.getUserID());

                    Params params = new Params();
                    params.put("BillID", billId);

                    return TaskHelper.receiveTask(paramsTask)
                            .map(aVoid -> {
                                taskEntity.setWorkID(aVoid);
                                taskEntity.setMainBillCode(taskEntity.getBillCode());
                                taskEntity.setMainBillID(taskEntity.getBillID());
                                return taskEntity;
                            })
                            .flatMap((Function<TaskEntity, ObservableSource<TaskEntity>>) task -> FineExApplication
                                    .component()
                                    .http()
                                    .loadReplenishOrderStatus(params)
                                    .map(new ResponseWrapper<>())
                                    .map(aVoid -> task));
                })
                .flatMap((Function<TaskEntity, ObservableSource<TaskEntity>>) taskEntity -> {
                    Params params = new Params();
                    params.put("workId", taskEntity.getWorkID());
                    UserEntity userInfo = FineExApplication.component().loginCache().getUserInfo();
                    params.put("executerId", userInfo.getUserID());
                    return TaskHelper.executeTask(params)
                            .map(aVoid -> taskEntity);
                })
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<TaskEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(TaskEntity info) {
                        mView.onSuccess(MessageCreator.createMessage(info, TASK));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }
}
